import type { ParamsData } from "@/api/user";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";
import { defineStore } from "pinia";
import {  showToast } from "vant";

export const useUserInfoStore = defineStore("userInfo", {
  state: () => {
    return {
      token: localStorage.getItem("token") || "",
      userInfo: {
        id:0,
        name:'',
        nickName: ''
      },
    };
  },
  actions: {
    //登录
    async login(loginParams: ParamsData) {
      try {
        const { token } = await reqLogin(loginParams);
        this.token = token;
        localStorage.setItem("token", token);
        return "ok";
      } catch (error) {
        console.log(error);
        return Promise.reject("fail");
      }
    },
    //退出登录
    async getLogout() {
      try {
        await reqLogout();
        // 清除用户相关信息
        this.reset()
        showToast("退出登录成功");
        return "ok";
      } catch (error) {
        showToast("退出登陆失败");
        return Promise.reject("fail");
      }
    },
    //获取用户信息
    async getUserInfo() {
      const res = await reqUserInfo();
      console.log(res);
      this.userInfo = res;
    },
    // 重置用户相关的信息  退出登录以及token过期
     reset() {
      this.token = "";
      localStorage.clear();
      this.userInfo = {
        id:0,
        name:'',
        nickName: ''
      }
    },
  },
});
